package com.example.module_motocircle.motocircle

import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.Router
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.base.BaseViewModel
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.Success
import com.example.lib_common.base.state.UILoader
import com.example.lib_common.base.state.UIState
import com.example.lib_common.base.utils.ToastUtils
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.tintDrawable
import com.example.module_motocircle.R
import com.example.module_motocircle.databinding.FragmentMotocircleBinding
import com.example.module_motocircle.databinding.LayoutCustomTabViewBinding
import com.example.module_motocircle.helper.SeriesPopupMenuRvHelper
import com.example.module_motocircle.information.InformationListFragment
import com.example.module_motocircle.model.NavigationItemModelItem
import com.example.module_motocircle.post.BlankListFragment
import com.example.module_motocircle.post.PostListFragment
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = Router.Ui.MotocircleFragment)
class MotocircleFragment : BaseFragment<MotocircleViewModel,FragmentMotocircleBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_motocircle
    private val mViewModel:MotocircleViewModel by activityViewModels()
    private lateinit var mUiLoader: UILoader

    private var mPostAdapter: ScreenSlidePagerAdapter? = null
    private var mSelectedPosition: Int = 0
    override fun initView() {
        this.initUILoader()
    }
    private var mediator: TabLayoutMediator? = null
    private fun initViewPager() {
        //适配器
        mPostAdapter = ScreenSlidePagerAdapter(mViewModel.mNavigationItem, this)
        mBinding.vp.adapter = mPostAdapter
        //默认选中帖子
        val default = mViewModel.mNavigationItem.find { it.defaultStatus == 1 }
        mSelectedPosition = if (default == null) 0 else mViewModel.mNavigationItem.indexOf(default)
        mBinding.vp.setCurrentItem(mSelectedPosition, false)
        //预加载机制
        mBinding.vp.offscreenPageLimit = 1
        //viewpager和tabLayout联动
        mBinding.vp.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
//                super.onPageSelected(position)
                mSelectedPosition = position
                setTabViewStyle(position)
            }
        })
        mediator = TabLayoutMediator(
            mBinding.tabLayout,
            mBinding.vp,
            true,
            true
        ) { tab, position -> //这里可以自定义TabView
            val tabView = DataBindingUtil.inflate<LayoutCustomTabViewBinding>(
                layoutInflater,
                R.layout.layout_custom_tab_view,
                null,
                false
            )
            if (position >= mViewModel.mNavigationItem.size) {
                return@TabLayoutMediator
            }
            val navigation = mViewModel.mNavigationItem[position]
            tabView.tab.text = navigation.title
            if (navigation.modelList == null || !navigation.modelList.any { it.checked }) {
                tabView.tab.text = mViewModel.mNavigationItem[position].title
            } else {
                tabView.tab.text = navigation.modelList.find { it.checked }?.name
            }
            tabView.ivArrow.visibility = if (navigation.modelList == null) View.GONE else View.VISIBLE
            tabView.lTab.setOnClickListener {
                if (!tab.isSelected) {
                    tab.select()
                    if (navigation.modelList != null) {
                        Handler(Looper.getMainLooper()).postDelayed({
                            showPopupList(
                                tabView.lTab,
                                navigation
                            )
                        }, 400)
                    }
                } else {
                    if (navigation.modelList != null) {
                        showPopupList(tabView.lTab, navigation)
                    }
                }
            }
            tab.customView = tabView.root
        }
        mediator?.attach()
    }
    private val popupMenuRvHelper by lazy {
        SeriesPopupMenuRvHelper(layoutInflater) { navigationId, modelItem ->
            val clickNavigation = mViewModel.mNavigationItem.find { it.navigationId == navigationId }
            clickNavigation?.modelList!!.forEach {
                it.checked = modelItem.modelId == it.modelId
            }
            mPostAdapter?.notifyDataSetChanged()
            setTabViewStyle(mSelectedPosition)
        }
    }
    private fun showPopupList(tabView: View, navigation: NavigationItemModelItem) {
        //val items = navigation.modelList!!.map { CommonPopupMenu(name = it.name) }
        popupMenuRvHelper.bindItems(navigation.navigationId, navigation.modelList!!)
        popupMenuRvHelper.show(tabView)
    }
    fun initUILoader() {
        mUiLoader = object : UILoader(requireContext()) {
            override fun loadSuccessView(container: ViewGroup?): View {
                return View(context)
            }
        }.apply { updateState(UIState.LOADING) }

        mBinding.lContainer.addView(mUiLoader)
    }
    override fun initListener() {
        mViewModel.navigationState.observeWithLifecycle(this) {
            when (it) {
                is Success -> {
                    if (mViewModel.mNavigationItem.isEmpty()) {
                        mUiLoader.updateState(UIState.EMPTY)
                    } else {
                        mUiLoader.updateState(UIState.SUCCESS)
                        handleNavigationData()
                    }
                }

                is Failed -> {
                    ToastUtils.showShort(requireActivity(), it.message)
                    mUiLoader.updateState(UIState.NETWORK_ERROR)
                }

                else -> {}
            }
        }
        mUiLoader.setOnRetryClickListener {
            initData()
        }
        mBinding.lSearch.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.MotocircleSearchActivity).withString("search_type", "all").navigation()
        }
    }
    private fun handleNavigationData() {
        initViewPager()
    }
    override fun initData() {
        mViewModel.getNavigationItem()
    }
    private inner class ScreenSlidePagerAdapter(private val item: List<NavigationItemModelItem>, fa: Fragment) : FragmentStateAdapter(fa) {

        override fun getItemCount(): Int = item.size

        override fun getItemId(position: Int): Long {
//            val navigation = item[position]
//            val checkModel = navigation.modelList?.find { it.checked }
//            if (checkModel != null) {
//                return checkModel.modelId.toLong()
//            }
            return item[position].navigationId.toLong()
        }


        override fun createFragment(position: Int): Fragment {
            val navigation = item[position]
            return when (navigation.type) {
                // 热门
                1 -> {
                    val modelItem = item[position].modelList?.find { it.checked }
                    if (modelItem?.modelId == "10001_01"){
                        PostListFragment.newInstance(sortType = "hot")
                    }else{
                        PostListFragment.newInstance(sortType = "hot")
                    }
                }
                // 帖子
                2 -> PostListFragment.newInstance(sortType = "new")
                // 资讯
                3 -> InformationListFragment()
                // 关注
                4 -> PostListFragment.newInstance(ifFocus = 1)
                else -> {
                    // 关注
                    BlankListFragment()
                }
            }
        }
    }
    private fun setTabViewStyle(defaultPosition: Int) {
        mViewModel.mNavigationItem.forEachIndexed { index, _ ->
            mBinding.tabLayout.run {
                val binding = getTabAt(index)?.customView?.let {
                    DataBindingUtil.getBinding<LayoutCustomTabViewBinding>(it)
                }
                if (defaultPosition == index) {
                    binding?.tab?.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.example.lib_common.R.color.color_d8000f
                        )
                    )
                    binding?.tab?.paint?.style = Paint.Style.FILL_AND_STROKE
                    val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_triangle)
                    //val tintDrawable = tintDrawable(drawable, Color.parseColor("#FFD8000F"))
                    val tintDrawable = tintDrawable(drawable, Color.parseColor("#FF919191"))
                    binding?.ivArrow?.setImageDrawable(tintDrawable)
                    binding?.tab?.paint?.strokeWidth = 0.8f
                } else {
                    binding?.tab?.setTextColor(
                        ContextCompat.getColor(
                            requireContext(),
                            com.example.lib_common.R.color.color_101010
                        )
                    )
                    binding?.tab?.paint?.style = Paint.Style.FILL_AND_STROKE
                    val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_triangle)
                    val tintDrawable = tintDrawable(drawable, Color.parseColor("#FF919191"))
                    binding?.ivArrow?.setImageDrawable(tintDrawable)
                    binding?.tab?.paint?.strokeWidth = 0f
                }

//                mBinding.tabLayout.getTabAt(index)?.view?.let {
//                    //ViewCompat.setPaddingRelative(mBinding.tabLayout.getTabAt(index)?.customView!!, 10.dp, 5.dp, 10.dp, 5.dp)
//                    ViewCompat.setPaddingRelative(it, 5.dp, 0, 5.dp, 0)
//                }

            }
        }
    }
}